package ua.edu.sumdu.j2se.roman.lab1.service;

import ua.edu.sumdu.j2se.roman.lab1.domain.ArrayTaskList;
import ua.edu.sumdu.j2se.roman.lab1.domain.Task;
import ua.edu.sumdu.j2se.roman.lab1.domain.TaskList;
import ua.edu.sumdu.j2se.roman.lab1.exceptions.FileSerializationException;
import ua.edu.sumdu.j2se.roman.lab1.util.Log;
import ua.edu.sumdu.j2se.roman.lab1.util.Utils;

import java.io.*;

/**
 * Author: Radko Roman.
 */

/**
 * This class provides serialization of tasks journal on the hard disk.
 *
 */
public class FileSerializationTasksService implements TasksService {
    /**
     * Contains file path.
     *
     */
    public static final String TASKS_FILE_PATH = "journal.bin";

    /**
     * Load list of tasks from the file.
     *
     * @return list of tasks
     * @throws FileSerializationException arises when could not found file with specified path
     */
    public TaskList loadList() throws FileSerializationException {
        TaskList result = new ArrayTaskList();
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(TASKS_FILE_PATH);
            ObjectInputStream oin = new ObjectInputStream(fis);
            Task[] tasks = (Task[]) oin.readObject();
            for (Task task : tasks) {
                result.add(task);
            }
        } catch (FileNotFoundException e) {
            String message = "File not found on the path: [" + TASKS_FILE_PATH + "]";
            Log.e(message);
            throw new FileSerializationException(message, e);
        } catch (IOException e) {
            throw new FileSerializationException(e);
        } catch (ClassNotFoundException e) {
            throw new FileSerializationException(e);
        } finally {
            Utils.closeQuietly(fis);
        }
        return result;
    }

    /**
     * Save list of tasks in the file.
     *
     * @param tasks                       list of tasks
     * @throws FileSerializationException arises when could not create file with specified path
     */
    public void saveList(TaskList tasks) throws FileSerializationException {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(TASKS_FILE_PATH);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(tasks.toArray());
            oos.flush();
        } catch (FileNotFoundException e) {
            String message = "Can't create file with path: [" + TASKS_FILE_PATH + "]";
            Log.e(message);
            throw new FileSerializationException(message, e);
        } catch (IOException e) {
            throw new FileSerializationException(e);
        } finally {
            Utils.closeQuietly(fos);
        }
    }

}
